<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Admin_Tucao extends Controller_DefaultTemplate{

public function action_index()
{
}

public function before()
{
	// Run anything that need ot run before this.
	parent::before();
}

public function action_list()
{
	$tucao_list = ORM::factory('tucao')->order_by('id', 'DESC')->find_all();
	$this->template->content = View::factory('book/tucao_list');
	$this->template->content->set('tucao_list', $tucao_list);
}

function GrabImage($url) { 
	if($url=="")
		return false; 
	$filename=strrchr($url,"/"); 
	ob_start(); 
	readfile($url); 
	$img = ob_get_contents(); 
	ob_end_clean(); 
	$size = strlen($img); 
	$fp2=@fopen($_SERVER['DOCUMENT_ROOT'].'/uploads/temp'.$filename, "a"); 
	fwrite($fp2,$img); 
	fclose($fp2); 
	return $_SERVER['DOCUMENT_ROOT'].'/uploads/temp'.$filename; 
} 

public function action_add()
{
	$url_json = arr::get($_GET, 'url_json');
	$url = json_decode($url_json);
	foreach ($url->url_json as $key => $value)
	{
		try
		{
			$filename = $this->GrabImage($value->url);
		}
		catch (ErrorException $e)
		{
			continue;
		}
		$tucao = ORM::factory("tucao")->where('url', '=', $value->url)->find();
		if ($filename AND !$tucao->loaded())
		{
			$image = Kohana_Image::factory($filename);
			$name = UUID::v4().".jpg";
			$file_path = $_SERVER['DOCUMENT_ROOT'].'/uploads/tucao/'.$name;
			$image->save($file_path, 80);

			$tucao = ORM::factory("tucao");
			$tucao->values(array(
				'image'       => $name,
				'url'		  => $value->url,
				'create_time' => time(),
			));
			$tucao->save();
		}
	}
}

public function action_delete()
{
	$tucao_id = $this->request->param('id');
	if ($tucao_id)
	{
		$tucao = ORM::factory('tucao')->where('id', '=', $tucao_id)->find();
		if ($tucao->loaded())
		{
			$tucao->delete();
			$this->request->redirect();
		}
	}
	
}

}




